<!--
 * @Author       : Hejh(3010733382@qq.com)
 * @Version      : V1.0
 * @Date         : 2024-02-22 19:15:14
 * @Description  : 添加或者更新用户面板
-->

<template>
  <!-- <n-card
    :size="'small'"
    style="width: 768px"
    role="dialog"
    title="添加用户"
    :bordered="false"
    aria-modal="true"
  >
    <template #header-extra>
      <SvgIcon
        icon="chacha"
        class="cursor-pointer"
        @click="handleClose"
      ></SvgIcon>
    </template> -->
  <n-form
    ref="userFormRef"
    :label-width="isSmall ? 100 : 120"
    label-placement="left"
    :label-align="isSmall ? 'left' : 'right'"
    :model="user"
    size="small"
    require-mark-placement="right"
    :rules="formRule"
  >
    <n-form-item label="登录账号：" path="username" class="!w-[400px]">
      <n-input
        v-model:value="user.username"
        :allow-input="noSideSpace"
        placeholder="请输入登录账号"
        clearable
        :maxlength="25"
      />
    </n-form-item>
    <n-form-item label="用户昵称：" path="nickname" class="!w-[400px]">
      <n-input
        v-model:value="user.nickname"
        :allow-input="noSideSpace"
        placeholder="请输入用户昵称"
        clearable
        :maxlength="50"
      />
    </n-form-item>
    <n-form-item label="密码：" path="password" class="!w-[400px]">
      <n-input
        show-password-on="click"
        type="password"
        v-model:value="user.password"
        :allow-input="noSideSpace"
        placeholder="不填则不修改"
        clearable
        :maxlength="20"
      />
    </n-form-item>

    <n-form-item label="个人空间大小：" path="sizeMax">
      <n-input-number
        :value="+convertBytes(user.sizeMax, 'GB')"
        @update:value="handleByteChange"
        :min="0"
        :max="2048"
        clearable
        placeholder="请输入空间大小"
      >
        <template #suffix> GB </template>
      </n-input-number>
      <div class="ml-[12px] text-gray-400 text-[12px]">(GB) 0则不限制</div>
    </n-form-item>

    <n-form-item label="更多：">
      <n-radio-group v-model:value="userInfoType" name="radiobuttongroup2">
        <n-radio-button :value="0">
          <SvgIcon
            icon="shezhi-shezhi-tianchong"
            :color="userInfoType === 0 ? '#fff' : '#999'"
            class="mr-1"
          ></SvgIcon>
          基础设置
        </n-radio-button>
        <n-radio-button :value="1">
          <SvgIcon
            icon="gengduo"
            :color="userInfoType === 1 ? '#fff' : '#999'"
          ></SvgIcon>
          更多设置
        </n-radio-button>
      </n-radio-group>
    </n-form-item>

    <MyTransition>
      <div v-if="userInfoType === 1">
        <n-form-item label="性别：" path="sex">
          <n-radio-group v-model:value="user.sex" name="radiogroup">
            <n-space>
              <n-radio :value="0"> 男 </n-radio>
              <n-radio :value="1"> 女 </n-radio>
            </n-space>
          </n-radio-group>
        </n-form-item>
        <n-form-item label="手机：" path="phone" class="!w-[400px]">
          <n-input
            v-model:value="user.phone"
            placeholder="请输入手机号："
            :allow-input="noSideSpace"
            clearable
            :maxlength="11"
          />
        </n-form-item>
        <n-form-item label="email：" path="email" class="!w-[400px]">
          <n-input
            v-model:value="user.email"
            placeholder="请输入邮箱："
            :allow-input="noSideSpace"
            :maxlength="50"
            clearable
          />
        </n-form-item>
      </div>
    </MyTransition>

    <n-divider class="!my-2" />

    <n-form-item label="角色权限：" path="roleId">
      <RoleSelect
        :default-role-id="user.roleId"
        :multiple="false"
        @change-value="handleRoleIdChange"
      ></RoleSelect>
    </n-form-item>
    <n-form-item label="所在部门：" path="departments">
      <AuthTable
        :target-list="targetList"
        class="!w-[100%]"
        @change-target-list="handleTargetListChange"
        @change-default-role-id="handleChangeDefaultRoleId"
        @change-default-size-max="handleChangeDefaultSizeMax"
      ></AuthTable>
    </n-form-item>

    <n-form-item label=" " path="defaultSizeMax">
      <n-popselect
        trigger="click"
        :options="[]"
        class="w-[300px]"
        display-directive="show"
        placement="right"
      >
        <template #header>
          <dep-select
            :root-dep="rootDep"
            @change-value="handleDepChange"
            :default-dep-ids="targetList.map((item) => item.id)"
          ></dep-select>
        </template>
        <template #empty> <div></div> </template>
        <n-button type="tertiary" class="text-[13px]">
          <svg-icon icon="tianjiatianjiayonghu11" class="mr-1"></svg-icon>
          添加部门
        </n-button>
      </n-popselect>
    </n-form-item>

    <n-divider class="!my-2" />
    <n-form-item label=" " v-permission="[PERMISSIONS.USER_EDIT]">
      <n-button type="primary" class="grent-btn w-[120px]" @click="handleSave">
        保存
      </n-button>
    </n-form-item>
  </n-form>
  <!-- </n-card> -->
</template>

<script setup lang="ts">
import type { FormInst } from 'naive-ui'
import type { UserNotDepRes, UserUpdateReq } from '@/types/user'
import { noSideSpace } from '@/utils'
import { convertBytes, convertToBytes } from '@/utils/index'
import { PERMISSIONS } from '@/constants/permission'
import { userMenuShow } from '@/hooks/useMenuShow'
import type { IndexObj } from '@/types/commom'

const props = defineProps<{
  isModify: boolean
  userRes?: UserNotDepRes
  rootDep?: IndexObj
}>()

const emits = defineEmits<{
  (e: 'visibleChange', value: boolean): void
  (e: 'changeUser', type: number, data: UserUpdateReq): void
}>()

const handleClose = () => {
  emits('visibleChange', false)
}

const { isSmall } = userMenuShow()

const userInfoType = ref(0)

// 用户所在部门授权
const authTableDefaultRoleId = ref('4')
const authTableDefaultSizeMax = ref('0')
const targetList = ref<IndexObj[]>([])
const handleDepChange = (value: string | string[], depsInfo: IndexObj[]) => {
  // 选择的对象发生了改变，[a,b,c]---->[a,b,f,g,h]
  // 权限信息同步修改，a，b的暂时不需要变更（authRolen）

  // targetList保留 value还在的，其他删除
  // target原先没有的，进行添加

  targetList.value = targetList.value.filter((item) => {
    return value.includes(item.id)
  })

  // target现在没有的
  let moreTargets = depsInfo
    .filter((item) => {
      return !targetList.value.some((item2) => {
        return item2.id === item.id
      })
    })
    .map((item3) => {
      return {
        sizeMax: authTableDefaultSizeMax.value,
        authRole: authTableDefaultRoleId.value,
        ...item3,
        targetName: item3.name,
        pTargetName: item3.parent.name
      }
    })

  targetList.value = targetList.value.concat(moreTargets)
  // handleDepsInfoChange()
}

const handleTargetListChange = (list: IndexObj[]) => {
  targetList.value = list
}

const handleChangeDefaultRoleId = (value: string) => {
  authTableDefaultRoleId.value = value
}

const handleChangeDefaultSizeMax = (value: string) => {
  authTableDefaultSizeMax.value = value
}

const user = reactive<UserUpdateReq>({
  username: '',
  nickname: '',
  password: '',
  sizeMax: '0',
  sex: 0,
  phone: '',
  email: '',
  roleId: '1',
  departments: []
})

const initUser = () => {
  if (props.isModify) {
    const {
      id,
      username,
      nickname,
      sizeMax,
      sex,
      phone,
      email,
      roleId,
      Departments
    } = props.userRes as UserNotDepRes
    user.userId = id
    user.username = username
    user.nickname = nickname
    user.sizeMax = sizeMax
    user.sex = sex
    user.phone = phone
    user.email = email
    user.roleId = roleId
    targetList.value = Departments.map((item) => {
      return {
        id: item.id,
        targetId: item.id,
        targetName: item.name,
        sizeMax: item.UserDepartment.sizeMax,
        authRole: item.UserDepartment.roleId,
        pTargetName: ''
      }
    })
  }
}

onMounted(() => {
  initUser()
})

const formRule = {
  username: [
    {
      required: true,
      message: '请输入用户账号名称',
      trigger: ['blur']
    },
    {
      min: 1,
      max: 50,
      trigger: ['blur'],
      message: '长度在1-50位'
    }
  ]
}

const userFormRef = ref<FormInst | null>(null)

const handleByteChange = (value: any) => {
  if (value === undefined || value === null || value === '') {
    return
  }
  if (!/^\d+$/.test(value)) {
    return
  }
  user.sizeMax = convertToBytes('' + value + 'GB')
}

const handleRoleIdChange = (value: string | string[]) => {
  user.roleId = value as string
}

const handleSave = () => {
  userFormRef.value?.validate((error: any) => {
    if (error) {
      return
    }

    user.departments = targetList.value.map((item) => {
      return {
        departmentId: item.id,
        sizeMax: item.sizeMax,
        roleId: item.authRole
      }
    })

    if (props.isModify) {
      emits('changeUser', 1, user)
    } else {
      emits('changeUser', 0, user)
    }
  })
}
</script>

<style scoped lang="scss"></style>
